package com.zsr.web;

import com.zsr.pojo.Book;
import com.zsr.pojo.Page;
import com.zsr.service.BookService;
import com.zsr.service.impl.BookServiceImpl;
import com.zsr.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ClientBookServlet extends BaseServlet {
    private BookService bookService=new BookServiceImpl();
    /**
     * 获得page对象，转发到前台Index列表页面
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("经过了前台的BookServlet");
        //1.获取请求的参数pageNo和pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"),1);
        int pageSize =WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        //2.调用BookService.page(pageNo,pageSize):page对象
        Page<Book> page =bookService.page(pageNo,pageSize);
        page.setUrl("client/bookServlet?action=page");
        //3.保存Page对象到request域中
        req.setAttribute("page",page);
        //4.请求转发到pages/manager/book_manager.jsp页面
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req,resp);
    }

    protected void pageByPrice(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int pageNo =WebUtils.parseInt(req.getParameter("pageNo"),1);
        int pageSize =WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        int min=WebUtils.parseInt(req.getParameter("min"),0);
        int max =WebUtils.parseInt(req.getParameter("max"),Integer.MAX_VALUE);
        Page<Book> page =bookService.pageByPrice(pageNo,pageSize,min,max);
        StringBuffer sb=new StringBuffer("client/bookServlet?action=pageByPrice");

        if( req.getParameter("min") !=null){
            sb.append("&min=").append(req.getParameter("min"));
        }
        if(req.getParameter("max")!=null){
            sb.append("&max=").append(req.getParameter("max"));

        }
        page.setUrl(sb.toString());
        req.setAttribute("page",page);
        req.getRequestDispatcher("/pages/client/index.jsp").forward(req,resp);

    }
}
